package com.zyfdroid.backupftpserver;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.documentfile.provider.DocumentFile;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;

public class SAFHelper {
    public SAFHelper(Context ctx) {
        this.ctx = ctx;
    }

    public List<SAFEntry> getAllSafs(){
        Set<String> sets = getSp().getStringSet("safs",new HashSet<String>());
        List<SAFEntry> result = new ArrayList<>();
        for (String str :
                sets) {
            result.add(SAFEntry.fromString(str));
        }
        return result;
    }

    private SharedPreferences getSp(){
        return ctx.getSharedPreferences("safs2",Context.MODE_PRIVATE);
    }

    public void registerEntry(String uri) throws UnsupportedOperationException{
        SAFEntry newEntry = new SAFEntry(ctx,uri);
        if(getByDisplayName(newEntry.displayName)!= null ){
            throw new UnsupportedOperationException("文件已经存在,请更换不同文件夹名");
        }
        SharedPreferences sps = getSp();
        Set<String> sets = new HashSet<>(sps.getStringSet("safs",new HashSet<String>()));
        sets.add(newEntry.toString());
        sps.edit().putStringSet("safs",sets).commit();
    }

    public void deleteEntry(SAFEntry entry){
        SharedPreferences sps = getSp();
        Set<String> sets = new HashSet<>(sps.getStringSet("safs",new HashSet<String>()));
        sets.remove((entry.toString()));
        ctx.getContentResolver().releasePersistableUriPermission(Uri.parse(entry.uri),(Intent.FLAG_GRANT_READ_URI_PERMISSION
                | Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
        sps.edit().putStringSet("safs",sets).commit();
    }

    public SAFEntry getByDisplayName(String displayName){
        for (SAFEntry ent :
                getAllSafs()) {
            if(ent.displayName.equals(displayName)){
                return ent;
            }
        }
        return null;
    }


    Context ctx;

    public static class SAFEntry{
        public String displayName;
        public String uri;

        @NonNull
        @Override
        public String toString() {
            return displayName+"/:"+uri;
        }

        public SAFEntry(Context ctx,String uri){
            this.uri = uri;
            this.displayName = DocumentFile.fromTreeUri(ctx, Uri.parse(uri)).getName();
        }
        private SAFEntry(String displayName,String uri){
            this.displayName = displayName;
            this.uri = uri;
        }

        public static SAFEntry fromString(String str){
            String[] data = str.split(Pattern.quote("/:"),2);
            return new SAFEntry(data[0],data[1]);
        }
    }

}
